package com.example.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.course.bean.Activity;
import com.example.course.converter.ActivityConverter;
import com.example.course.dto.ActivityDTO;
import com.example.course.service.ActivityService;
import com.example.course.mapper.ActivityMapper;
import com.example.course.vo.ActivityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Jasmine-drs
 * @description 针对表【activity(活动表)】的数据库操作Service实现
 * @createDate 2025-04-22 15:36:40
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity>
		implements ActivityService {

	@Autowired
	private ActivityConverter activityConverter;

	@Override
	public Page<ActivityVO> listActivities(long current, long size) {
		// 查询数据库
		Page<Activity> page = new Page<>(current, size);
		QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("create_time");
		Page<Activity> activityPage = this.page(page, queryWrapper);

		// 转换为VO
		List<ActivityVO> activityVOList = activityConverter.toVOList(activityPage.getRecords());

		// 封装结果
		Page<ActivityVO> resultPage = new Page<>(activityPage.getCurrent(), activityPage.getSize(), activityPage.getTotal());
		resultPage.setRecords(activityVOList);

		return resultPage;
	}

	@Override
	public ActivityVO getActivityById(Integer id) {
		Activity activity = this.getById(id);
		if (activity == null) {
			throw new RuntimeException("活动不存在");
		}
		return activityConverter.toVO(activity);
	}

	@Override
	public ActivityVO addActivity(ActivityDTO activityDTO) {
		// DTO转换为实体
		Activity activity = activityConverter.toEntity(activityDTO);

		// 保存数据库
		boolean success = this.save(activity);
		if (!success) {
			throw new RuntimeException("添加活动失败");
		}

		// 转换为VO并返回
		return activityConverter.toVO(activity);
	}
}




